package com.lxl.plugin.packagejar.util;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by LXLong on 2015/3/2.
 */
public class Util {

    public static boolean matchFileNamingConventions(String fileName) {
        return fileName.matches("[^/\\\\<>*?|\"]+");
    }

    public static void iterateDirectory(Project project, HashSet<VirtualFile> directories, VirtualFile directory) {
        PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(directory);
        if (directory != null) {
            directories.add(psiDirectory.getVirtualFile());
            PsiDirectory[] psiDirectories = psiDirectory.getSubdirectories();
            for (PsiDirectory pd : psiDirectories) {
                iterateDirectory(project, directories, pd.getVirtualFile());
            }
        }
    }

    public static String getTheSameStart(List<String> strings) {
        if (strings == null || strings.size() == 0) {
            return "";
        }
        int max = 888888;
        for (String string : strings) {
            if (string.length() < max) {
                max = string.length();
            }
        }
        StringBuilder sb = new StringBuilder();
        HashSet set = new HashSet();
        for (int i = 0; i < max; i++) {
            for (String string : strings) {
                set.add(string.charAt(i));
            }
            if (set.size() == 1) {
                sb.append(set.iterator().next());
            } else {
                break;
            }
            set.clear();
        }
        return sb.toString();
    }


    private static int getMinorVersion(String vs) {
        final int dashIndex = vs.lastIndexOf('_');
        if (dashIndex >= 0) {
            StringBuilder builder = new StringBuilder();
            for (int idx = dashIndex + 1; idx < vs.length(); idx++) {
                final char ch = vs.charAt(idx);
                if (Character.isDigit(ch)) {
                    builder.append(ch);
                } else {
                    break;
                }
            }
            if (builder.length() > 0) {
                try {
                    return Integer.parseInt(builder.toString());
                } catch (NumberFormatException ignored) {
                }
            }
        }
        return 0;
    }

    public static String getJDKPath(Project project) {
        final String vmExecutablePath;
        JavaSdkVersion sdkVersion = null;
        Sdk projectJdk = null;
        int sdkMinorVersion = 0;
        Set<Sdk> candidates = new HashSet<Sdk>();
        Sdk defaultSdk = ProjectRootManager.getInstance(project).getProjectSdk();
        if (defaultSdk != null && defaultSdk.getSdkType() instanceof JavaSdkType) {
            candidates.add(defaultSdk);
        }
        for (Module module : ModuleManager.getInstance(project).getModules()) {
            final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
            if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
                candidates.add(sdk);
            }
        }
        JavaSdk javaSdkType = JavaSdk.getInstance();
        for (Sdk candidate : candidates) {
            final String vs = candidate.getVersionString();
            if (vs != null) {
                final JavaSdkVersion candidateVersion = javaSdkType.getVersion(vs);
                if (candidateVersion != null) {
                    final int candidateMinorVersion = getMinorVersion(vs);
                    if (projectJdk == null) {
                        sdkVersion = candidateVersion;
                        sdkMinorVersion = candidateMinorVersion;
                        projectJdk = candidate;
                    } else {
                        final int result = candidateVersion.compareTo(sdkVersion);
                        if (result > 0 || (result == 0 && candidateMinorVersion > sdkMinorVersion)) {
                            sdkVersion = candidateVersion;
                            sdkMinorVersion = candidateMinorVersion;
                            projectJdk = candidate;
                        }
                    }
                }
            }
        }
        Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
        if (projectJdk == null || sdkVersion == null || !sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_6)) {
            projectJdk = internalJdk;
        }
        JavaSdkType projectJdkType = (JavaSdkType) projectJdk.getSdkType();
        vmExecutablePath = projectJdkType.getVMExecutablePath(projectJdk);

        return vmExecutablePath.substring(0, vmExecutablePath.length() - 4);
    }

}
